package org.example.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.example.common.exception.ServiceException;
import org.example.common.util.JWTUtil;
import org.example.user.dao.entity.User;
import org.example.user.dao.mapper.UserMapper;
import org.example.user.dto.req.UserLoginReqDTO;
import org.example.user.dto.req.UserLogoutReqDTO;
import org.example.user.dto.req.UserRegisterReqDTO;
import org.example.user.dto.resp.UserLoginRespDTO;
import org.example.user.dto.resp.UserLogoutRespDTO;
import org.example.user.dto.resp.UserRegisterRespDTO;
import org.example.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private StringRedisTemplate redis;
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        String username = userLoginReqDTO.getUsername();
        String password = userLoginReqDTO.getPassword();

        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, username)
                .eq(User::getPassword,password);
        User user = userMapper.selectOne(queryWrapper);
        if(username == null){
            throw new ServiceException("用户名不存在");
        }
        String jwt = JWTUtil.createToken(username);
        redis.opsForValue().set(username, jwt, 200, TimeUnit.SECONDS);

        return new UserLoginRespDTO(username,jwt);
    }

    @Override
    public UserLogoutRespDTO logout(UserLogoutReqDTO userLogoutReqDTO) {
        redis.delete(userLogoutReqDTO.getUsername());
        return new UserLogoutRespDTO(userLogoutReqDTO.getUsername());
    }

    @Override
    public UserRegisterRespDTO register(UserRegisterReqDTO userRegisterReqDTO) {
        String username = userRegisterReqDTO.getUsername();
        String password = userRegisterReqDTO.getPassword();
        userMapper.insert(new User(null,username,password));
        return new UserRegisterRespDTO(username);
    }
}
